import 'package:animated_transitions/animated_transitions.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:redux/redux.dart';
import 'package:vamos/core/index.dart';
import '../../core/widgets/report_dialog.dart';
import 'ai_chat_page.dart';
import '../profile/other_profile_page.dart';

/// 问答详情界面
class VamosQADetailInterface extends StatefulWidget {
  final QuestionEntity question;

  const VamosQADetailInterface({super.key, required this.question});

  @override
  State<VamosQADetailInterface> createState() => _VamosQADetailInterfaceState();
}

class _VamosQADetailInterfaceState extends State<VamosQADetailInterface> {
  late ReduxQAManager _qaManager;
  late ReduxUserManager _userManager;
  final TextEditingController _commentController = TextEditingController();
  bool _showAIPopup = true;

  // 点赞状态管理
  bool _isQuestionLiked = false;
  Map<String, bool> _answerLikedStatus = {};

  @override
  void initState() {
    super.initState();
    _qaManager = serviceLocator<ReduxQAManager>();
    _userManager = serviceLocator<ReduxUserManager>();

    // 初始化点赞状态
    _initializeLikeStates();
  }

  /// 初始化点赞状态
  void _initializeLikeStates() {
    final currentUser = _userManager.getCurrentUser();
    if (currentUser != null) {
      // 从AppState中获取最新的问题数据
      final appState = _qaManager.store.state;
      final questionList =
          appState.qaState.questionCollection
              .where((q) => q.questionId == widget.question.questionId)
              .toList();
      final currentQuestion =
          questionList.isNotEmpty ? questionList.first : null;

      if (currentQuestion != null) {
        // 检查问题是否被当前用户点赞
        _isQuestionLiked = currentQuestion.likedUserIds.contains(
          currentUser.uniqueId,
        );
      }

      // 从AppState中获取该问题的所有回答
      final answers =
          appState.qaState.answerCollection
              .where((a) => a.questionId == widget.question.questionId)
              .toList();

      for (final answer in answers) {
        _answerLikedStatus[answer.answerId] = answer.likedUserIds.contains(
          currentUser.uniqueId,
        );
      }
    }
  }

  /// 检查用户是否登录
  bool _isUserLoggedIn() {
    return _userManager.getCurrentUser() != null;
  }

  /// 获取当前问题的点赞数
  int _getCurrentQuestionLikeCount() {
    final appState = _qaManager.store.state;
    final questionList =
        appState.qaState.questionCollection
            .where((q) => q.questionId == widget.question.questionId)
            .toList();
    final currentQuestion = questionList.isNotEmpty ? questionList.first : null;

    if (currentQuestion != null) {
      return currentQuestion.likeCount;
    }

    return widget.question.likeCount;
  }

  /// 获取当前回答的点赞数
  int _getCurrentAnswerLikeCount(AnswerEntity answer) {
    final appState = _qaManager.store.state;
    final answerList =
        appState.qaState.answerCollection
            .where((a) => a.answerId == answer.answerId)
            .toList();
    final currentAnswer = answerList.isNotEmpty ? answerList.first : null;

    if (currentAnswer != null) {
      return currentAnswer.likeCount;
    }

    return answer.likeCount;
  }

  @override
  void dispose() {
    _commentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 主内容
          Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my_background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: Column(
                children: [
                  // 顶部导航栏
                  _buildTopNavigationBar(),

                  // 主要内容区域
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 问题作者信息
                          _buildAuthorSection(),

                          // 问题图片
                          _buildQuestionImage(),

                          // 问题标题
                          _buildQuestionTitle(),

                          // 互动数据
                          _buildEngagementSection(),

                          // 评论列表
                          _buildCommentsSection(),
                        ],
                      ),
                    ),
                  ),

                  // 底部评论输入框
                  _buildCommentInputSection(),
                ],
              ),
            ),
          ),

          // 浮动AI提示框 - 最高层
          if (_showAIPopup)
            Positioned(
              top: 80.h,
              right: 16.w,
              child: SizedBox(
                width: 264.w,
                child: AspectRatio(
                  aspectRatio: 264 / 80,
                  child: Image.asset(
                    'assets/images/ask_ai.png',
                    fit: BoxFit.cover,
                  ).inkWell(
                    onTap: () {
                      setState(() {
                        _showAIPopup = false;
                      });
                    },
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          Icon(
            Icons.arrow_back,
            color: Colors.white,
            size: 26.w,
          ).inkWell(onTap: () => Navigator.pop(context)),

          // 标题
          Expanded(
            child:
                Text('DETAILS')
                    .fontSize(20.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w700,
                      ).fontFamily!,
                    )
                    .center(),
          ),

          // AI按钮
          Image.asset(
            'assets/images/ai.png',
            width: 35.w,
            height: 35.w,
          ).inkWell(
            onTap: () {
              _navigateToAIChat();
            },
          ),
        ],
      ),
    );
  }

  /// 构建作者信息区域
  Widget _buildAuthorSection() {
    final author = _userManager.getUserById(widget.question.authorId);

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 作者头像
          Container(
            width: 60.w,
            height: 60.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.white, width: 2.w),
            ),
            child: ClipOval(
              child:
                  author != null
                      ? Image.asset(
                        author.profileImage,
                        width: 50.w,
                        height: 50.w,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Icon(
                            Icons.person,
                            size: 24.w,
                            color: Colors.grey[600],
                          ).center();
                        },
                      )
                      : Icon(
                        Icons.person,
                        size: 24.w,
                        color: Colors.grey[600],
                      ).center(),
            ),
          ).inkWell(onTap: () => _navigateToUserProfile(author)),

          SizedBox(width: 12.w),

          // 作者信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 用户名
                Text(author?.displayName ?? 'Unknown User')
                    .fontSize(16.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w600,
                      ).fontFamily!,
                    ),

                SizedBox(height: 4.h),

                // 个人简介
                Text(
                  author?.personalBio ?? 'No bio available',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.white,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                  ),

                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),

          Image.asset(
            'assets/images/report.png',
            width: 24.w,
            height: 24.w,
          ).inkWell(
            onTap: () {
              _handleQuestionReport();
            },
          ),
        ],
      ),
    );
  }

  /// 构建问题图片
  Widget _buildQuestionImage() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      child: AspectRatio(
        aspectRatio: 343 / 282,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12.r),
          child: Stack(
            children: [
              // 图片内容
              if (widget.question.mediaType == QAMediaType.image &&
                  widget.question.mediaUrl != null)
                Image.asset(
                  widget.question.mediaUrl!,
                  width: double.infinity,
                  height: double.infinity,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      width: double.infinity,
                      height: double.infinity,
                      color: Colors.grey[800],
                      child:
                          Icon(
                            Icons.image,
                            size: 48.w,
                            color: Colors.grey[600],
                          ).center(),
                    );
                  },
                )
              else if (widget.question.mediaType == QAMediaType.video &&
                  widget.question.thumbnailUrl != null)
                Image.asset(
                  widget.question.thumbnailUrl!,
                  width: double.infinity,
                  height: double.infinity,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      width: double.infinity,
                      height: double.infinity,
                      color: Colors.grey[800],
                      child:
                          Icon(
                            Icons.video_library,
                            size: 48.w,
                            color: Colors.grey[600],
                          ).center(),
                    );
                  },
                )
              else
                Container(
                  width: double.infinity,
                  height: double.infinity,
                  color: Colors.grey[800],
                  child:
                      Icon(
                        widget.question.mediaType == QAMediaType.video
                            ? Icons.video_library
                            : Icons.quiz,
                        size: 48.w,
                        color: Colors.grey[600],
                      ).center(),
                ),

              // 视频播放图标
              if (widget.question.mediaType == QAMediaType.video)
                SizedBox(
                  width: double.infinity,
                  height: double.infinity,
                  child:
                      Icon(
                        Icons.play_circle_filled,
                        size: 64.w,
                        color: Colors.white.withOpacity(0.8),
                      ).center(),
                ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建问题标题
  Widget _buildQuestionTitle() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Text(widget.question.title)
          .fontSize(16.sp)
          .textColor(Colors.white)
          .fontFamily(
            GoogleFonts.poppins(fontWeight: FontWeight.w600).fontFamily!,
          ),
    );
  }

  /// 构建互动数据区域
  Widget _buildEngagementSection() {
    return StreamBuilder(
      stream: _qaManager.store.onChange,
      builder: (context, snapshot) {
        // 从AppState中获取最新的问题数据
        final appState = _qaManager.store.state;
        final questionList =
            appState.qaState.questionCollection
                .where((q) => q.questionId == widget.question.questionId)
                .toList();
        final currentQuestion =
            questionList.isNotEmpty ? questionList.first : null;
        final answerCount =
            currentQuestion?.answerCount ?? widget.question.answerCount;

        return Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              // 点赞
              Row(
                children: [
                  Image.asset(
                    _isQuestionLiked
                        ? 'assets/images/like_fill.png'
                        : 'assets/images/like.png',
                    width: 20.w,
                    height: 20.w,
                  ).inkWell(onTap: _handleQuestionLike),
                  SizedBox(width: 4.w),
                  Text(
                    '${_getCurrentQuestionLikeCount()}',
                  ).fontSize(14.sp).textColor(Colors.white),
                ],
              ),

              SizedBox(width: 24.w),

              // 评论
              Row(
                children: [
                  Image.asset(
                    'assets/images/comment.png',
                    width: 20.w,
                    height: 20.w,
                  ),
                  SizedBox(width: 4.w),
                  Text('$answerCount').fontSize(14.sp).textColor(Colors.white),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建评论列表区域
  Widget _buildCommentsSection() {
    return StreamBuilder(
      stream: _qaManager.store.onChange,
      builder: (context, snapshot) {
        // 从AppState中获取最新的回答数据
        final appState = _qaManager.store.state;
        final answers =
            appState.qaState.answerCollection
                .where((a) => a.questionId == widget.question.questionId)
                .toList();

        return Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              // 评论标题
              Text('${answers.length} Comments In Total')
                  .fontSize(16.sp)
                  .textColor(Colors.white)
                  .fontFamily(
                    GoogleFonts.poppins(
                      fontWeight: FontWeight.w600,
                    ).fontFamily!,
                  ),

              SizedBox(height: 16.h),

              // 评论列表或空状态
              if (answers.isEmpty)
                _buildEmptyCommentsState()
              else
                ...answers
                    .map((answer) => _buildCommentItem(answer, answers))
                    .toList(),
            ],
          ),
        );
      },
    );
  }

  /// 构建空评论状态
  Widget _buildEmptyCommentsState() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 40.h),
      child: Column(
        children: [
          Image.asset(
            'assets/images/empty.png',
            width: 80.w,
            height: 80.w,
            fit: BoxFit.contain,
          ),
          SizedBox(height: 16.h),
          Text('No answers yet')
              .fontSize(14.sp)
              .textColor(Colors.white.withOpacity(0.7))
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily!,
              ),
          SizedBox(height: 4.h),
          Text('Be the first to answer!')
              .fontSize(12.sp)
              .textColor(Colors.white.withOpacity(0.5))
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w300).fontFamily!,
              ),
        ],
      ),
    );
  }

  /// 构建单个评论项
  Widget _buildCommentItem(AnswerEntity answer, List<AnswerEntity> allAnswers) {
    final author = _userManager.getUserById(answer.authorId);
    // 找到所有回答中点赞数最高的
    final maxLikes =
        allAnswers.isNotEmpty
            ? allAnswers.map((a) => a.likeCount).reduce((a, b) => a > b ? a : b)
            : 0;
    final isBestAnswer = answer.likeCount == maxLikes && maxLikes > 0;

    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Stack(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 评论者头像
              Container(
                width: 40.w,
                height: 40.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(
                    color: Colors.white.withOpacity(0.2),
                    width: 1,
                  ),
                ),
                child: ClipOval(
                  child:
                      author != null
                          ? Image.asset(
                            author.profileImage,
                            width: 40.w,
                            height: 40.w,
                            fit: BoxFit.cover,
                            errorBuilder: (context, error, stackTrace) {
                              return Icon(
                                Icons.person,
                                size: 20.w,
                                color: Colors.grey[600],
                              ).center();
                            },
                          )
                          : Icon(
                            Icons.person,
                            size: 20.w,
                            color: Colors.grey[600],
                          ).center(),
                ),
              ).inkWell(onTap: () => _navigateToUserProfile(author)),

              SizedBox(width: 12.w),

              // 评论内容
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户名和最佳答案标签
                    Row(
                      children: [
                        Text(author?.displayName ?? 'Unknown User')
                            .fontSize(14.sp)
                            .textColor(Colors.white)
                            .fontFamily(
                              GoogleFonts.poppins(
                                fontWeight: FontWeight.w600,
                              ).fontFamily!,
                            ),

                        if (isBestAnswer) ...[
                          SizedBox(width: 8.w),
                          Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 8.w,
                              vertical: 2.h,
                            ),
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                begin: Alignment(0.00, 0.35),
                                end: Alignment(1.00, 1.00),
                                colors: [
                                  const Color(0xFF83BE4A),
                                  const Color(0xFFF3E3C6),
                                  const Color(0xFFFB894E),
                                ],
                              ),
                              borderRadius: BorderRadius.circular(4.r),
                            ),
                            child: Text('Best Answer')
                                .fontSize(10.sp)
                                .textColor(Colors.black)
                                .fontFamily(
                                  GoogleFonts.poppins(
                                    fontWeight: FontWeight.w700,
                                  ).fontFamily!,
                                ),
                          ),
                        ],
                      ],
                    ),

                    SizedBox(height: 4.h),

                    // 个人简介
                    Text(
                      author?.personalBio ?? 'No bio available',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.grey[400],
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),

                    SizedBox(height: 8.h),

                    // 评论内容
                    Text(answer.content)
                        .fontSize(14.sp)
                        .textColor(Colors.white)
                        .fontFamily(
                          GoogleFonts.poppins(
                            fontWeight: FontWeight.w400,
                          ).fontFamily!,
                        ),
                  ],
                ),
              ),
            ],
          ),

          // 右上角按钮
          Positioned(
            top: 0,
            right: 0,
            child: Row(
              children: [
                // 点赞按钮
                Row(
                  children: [
                    Image.asset(
                      (_answerLikedStatus[answer.answerId] ?? false)
                          ? 'assets/images/like_fill.png'
                          : 'assets/images/like.png',
                      width: 16.w,
                      height: 16.w,
                    ).inkWell(onTap: () => _handleAnswerLike(answer)),
                    SizedBox(width: 4.w),
                    Text(
                      '${_getCurrentAnswerLikeCount(answer)}',
                    ).fontSize(12.sp).textColor(Colors.white),
                  ],
                ),

                SizedBox(width: 12.w),

                // 举报按钮
                Image.asset(
                  'assets/images/report.png',
                  width: 16.w,
                  height: 16.w,
                ).inkWell(onTap: () => _handleAnswerReport(answer)),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建评论输入区域
  Widget _buildCommentInputSection() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(color: Colors.transparent),
      child: Container(
        height: 40.h,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(6.r),
        ),
        child: Row(
          children: [
            // 输入框
            Expanded(
              child: TextField(
                controller: _commentController,
                style: TextStyle(color: Colors.black, fontSize: 14.sp),
                decoration: InputDecoration(
                  hintText: 'Input Content',
                  hintStyle: TextStyle(
                    color: Colors.grey[500],
                    fontSize: 14.sp,
                  ),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 0.h, // 让文本垂直居中
                  ),
                  isDense: true, // 减少默认高度
                ),
                textAlignVertical: TextAlignVertical.center, // 文本垂直居中
              ),
            ),

            // 发送按钮
            Padding(
              padding: EdgeInsets.only(right: 8.w),
              child: Image.asset(
                'assets/images/send_answer.png',
                width: 24.w,
                height: 24.w,
              ).inkWell(
                onTap: () {
                  _submitComment();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 提交评论
  void _submitComment() async {
    final content = _commentController.text.trim();
    if (content.isEmpty) return;

    // 检查用户是否登录
    if (!_isUserLoggedIn()) {
      VamosLoginRequiredDialog.showLoginRequiredDialog(context);
      return;
    }

    final currentUser = _userManager.getCurrentUser();
    if (currentUser == null) return;

    try {
      // 创建新的回答实体
      final newAnswer = AnswerEntity(
        answerId: 'answer_${DateTime.now().millisecondsSinceEpoch}',
        questionId: widget.question.questionId,
        authorId: currentUser.uniqueId,
        content: content,
        answerTime: DateTime.now(),
        likeCount: 0,
        likedUserIds: [],
      );

      // 提交回答到Redux
      final success = await _qaManager.addAnswer(newAnswer);

      if (success) {
        // 清空输入框
        _commentController.clear();
        // 更新UI
        setState(() {
          // 触发UI更新
        });

        // 显示成功提示
        NotificationUtils.showSuccess(context, message: 'Reply Success.');
      } else {
        NotificationUtils.showError(context, message: 'Reply Failed.');
      }
    } catch (e) {
      // 显示错误提示
      NotificationUtils.showError(context, message: 'Reply Failed: $e');
    }
  }

  /// 处理问题点赞
  void _handleQuestionLike() async {
    // 检查用户是否登录
    if (!_isUserLoggedIn()) {
      VamosLoginRequiredDialog.showLoginRequiredDialog(context);
      return;
    }

    final currentUser = _userManager.getCurrentUser();
    if (currentUser == null) return;

    try {
      setState(() {
        _isQuestionLiked = !_isQuestionLiked;
      });

      if (_isQuestionLiked) {
        // 点赞
        final success = await _qaManager.likeQuestion(
          widget.question.questionId,
          currentUser.uniqueId,
        );
        if (success) {
        } else {
          // 回滚状态
          setState(() {
            _isQuestionLiked = !_isQuestionLiked;
          });
        }
      } else {
        // 取消点赞
        final success = await _qaManager.unlikeQuestion(
          widget.question.questionId,
          currentUser.uniqueId,
        );
        if (success) {
        } else {
          // 回滚状态
          setState(() {
            _isQuestionLiked = !_isQuestionLiked;
          });
        }
      }
    } catch (e) {
      // 回滚状态
      setState(() {
        _isQuestionLiked = !_isQuestionLiked;
      });
    }
  }

  /// 处理回答点赞
  void _handleAnswerLike(AnswerEntity answer) async {
    final answerId = answer.answerId;
    final isLiked = _answerLikedStatus[answerId] ?? false;

    // 检查用户是否登录
    if (!_isUserLoggedIn()) {
      VamosLoginRequiredDialog.showLoginRequiredDialog(context);
      return;
    }

    final currentUser = _userManager.getCurrentUser();
    if (currentUser == null) return;

    try {
      setState(() {
        _answerLikedStatus[answerId] = !isLiked;
      });

      if (!isLiked) {
        // 点赞
        final success = await _qaManager.likeAnswer(
          answerId,
          currentUser.uniqueId,
        );
        if (success) {
        } else {
          // 回滚状态
          setState(() {
            _answerLikedStatus[answerId] = isLiked;
          });
        }
      } else {
        // 取消点赞
        final success = await _qaManager.unlikeAnswer(
          answerId,
          currentUser.uniqueId,
        );
        if (success) {
        } else {
          // 回滚状态
          setState(() {
            _answerLikedStatus[answerId] = isLiked;
          });
        }
      }
    } catch (e) {
      // 回滚状态
      setState(() {
        _answerLikedStatus[answerId] = isLiked;
      });
    }
  }

  /// 处理问题举报
  void _handleQuestionReport() {
    showVamosReportDialog(
      context: context,
      title: 'Report Question',
      subtitle: 'Please select a reason for reporting this question.',
      onReportSubmitted: (VamosReportOption option) {
        _deleteQuestionAndExit();
      },
    );
  }

  /// 删除当前问题并返回上一页
  void _deleteQuestionAndExit() async {
    try {
      final success = await _qaManager.deleteQuestion(
        widget.question.questionId,
      );
      if (success) {
        NotificationUtils.showSuccess(
          context,
          message: 'You won\'t see this again.',
        );
        Navigator.pop(context);
      } else {
        NotificationUtils.showError(
          context,
          message: 'Failed to report question.',
        );
      }
    } catch (e) {
      NotificationUtils.showError(
        context,
        message: 'Error reporting question: $e',
      );
    }
  }

  /// 处理回答举报
  void _handleAnswerReport(AnswerEntity answer) {
    showVamosReportDialog(
      context: context,
      title: 'Report Comment',
      subtitle: 'Please select a reason for reporting this comment.',
      onReportSubmitted: (VamosReportOption option) {
        _deleteAnswer(answer.answerId);
      },
    );
  }

  /// 跳转到AI对话页面
  void _navigateToAIChat() {
    Navigator.push(
      context,
      PageRouteBuilder(
        pageBuilder:
            (context, animation, secondaryAnimation) => VamosAIChatInterface(
              question: widget.question,
              initialMessage: widget.question.title,
            ),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          return SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(1.0, 0.0),
              end: Offset.zero,
            ).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeInOut),
            ),
            child: child,
          );
        },
        transitionDuration: Duration(milliseconds: 300),
      ),
    );
  }

  void _deleteAnswer(String answerId) async {
    try {
      final success = await _qaManager.deleteAnswer(answerId);

      if (success) {
        setState(() {
          _answerLikedStatus.remove(answerId);
        });

        NotificationUtils.showSuccess(
          context,
          message: 'You won\'t see this again.',
        );
      } else {
        NotificationUtils.showError(
          context,
          message: 'Failed to report comment.',
        );
      }
    } catch (e) {
      NotificationUtils.showError(
        context,
        message: 'Error reporting comment: $e',
      );
    }
  }

  /// 跳转到用户主页
  void _navigateToUserProfile(UserDataEntity? user) {
    if (user == null) return;

    // 检查是否是当前用户，如果是则不跳转
    final currentUser = _userManager.getCurrentUser();
    if (currentUser != null && currentUser.uniqueId == user.uniqueId) {
      return;
    }

    // 跳转到其他用户主页
    Navigator.of(context).push(
      TransitionPageRoute(
        builder:
            (context) => StoreProvider<AppState>(
              store: serviceLocator<Store<AppState>>(),
              child: VamosOtherProfileInterface(user: user),
            ),
        transitionAnimation: BrushStrokeTransition(
          direction: TransitionDirection.right,
          colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
        ),
      ),
    );
  }
}
